
package com.eltonkent.ui;

import java.util.ArrayList;

import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;

import com.eltonkent.R;
import com.eltonkent.templates.SafeTemplateFactory;
import com.eltonkent.ui.adapters.SimpleIconListAdapter;
import com.eltonkent.ui.containers.SimpleIconListContainer;
import com.eltonkent.ui.containers.TemplateFieldContainer;

public class TemplateListActivity extends ParentActivity
{
	private ListView list;

	private AdapterView.OnItemClickListener listClickListener = new AdapterView.OnItemClickListener()
	{
		@Override
		public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3)
		{
			SimpleIconListContainer selectedItem = (SimpleIconListContainer) list.getAdapter()
					.getItem(arg2);
			Log.d("UI", "SELECTED item ->" + selectedItem);

			ArrayList<TemplateFieldContainer> entryFieldList = SafeTemplateFactory.getFieldContainerList(
					getApplicationContext(), selectedItem.getTemplateName());
			Intent intent = new Intent();
			intent.putParcelableArrayListExtra(ApplicationConstants.EXTRA_FIELD_CONTAINER, entryFieldList);
			intent.putExtra(ApplicationConstants.EXTRA_TEMPLATE_ICON, selectedItem.getIconResource());
			intent.putExtra(ApplicationConstants.EXTRA_TEMPLATE, selectedItem.getTemplateName());
			setResult(RESULT_OK, intent);
			removeTextOnlyFromPath(getResources().getString(R.string.template_select_title));
			finish();
		}
	};

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event)
	{
		if(keyCode == KeyEvent.KEYCODE_BACK)
		{
			closeActivity(RESULT_CANCELED, getResources().getString(R.string.template_select_title));
			return true;
		}
		return false;
	}

	@Override
	protected void populateUI()
	{

		addToPath(getResources().getString(R.string.template_select_title));
		refreshList();
	}

	private void refreshList()
	{
		SimpleIconListAdapter adapter = new SimpleIconListAdapter(getApplicationPreferences(),
				getApplicationContext(), R.layout.listview_icon_singleline_templates, SafeTemplateFactory
						.getTemplateList(getApplicationContext(), R.xml.templates));
		list.setAdapter(adapter);
		setStatusText(adapter.getCount() + " " + getResources().getString(R.string.total_items));

	}

	@Override
	protected void setupUI(Bundle savedInstance)
	{
		setContentView(R.layout.activity_genericlist);
		list = (ListView) findViewById(R.id.folderList);
		list.setDividerHeight(0);
		list.setOnItemClickListener(listClickListener);
	}

}
